<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderId">
        <el-input
            v-model="queryParams.orderId"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select style="width: 200px;" v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option
              v-for="dict in order_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" style="width: 450px">
        <el-date-picker
            v-model="daterangeOrderTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">-->
      <!--  <el-button-->
      <!--      type="primary"-->
      <!--      plain-->
      <!--      icon="Plus"-->
      <!--      @click="handleAdd"-->
      <!--      v-hasPermi="['orderManagement:MaintenanceOrder:add']"-->
      <!--  >新增-->
      <!--  </el-button>-->
      <!--</el-col>-->
      <!--<el-col :span="1.5">-->
      <!--  <el-button-->
      <!--      type="success"-->
      <!--      plain-->
      <!--      icon="Edit"-->
      <!--      :disabled="single"-->
      <!--      @click="handleUpdate"-->
      <!--      v-hasPermi="['orderManagement:MaintenanceOrder:edit']"-->
      <!--  >修改-->
      <!--  </el-button>-->
      <!--</el-col>-->
      <!--<el-col :span="1.5">-->
      <!--  <el-button-->
      <!--      type="danger"-->
      <!--      plain-->
      <!--      icon="Delete"-->
      <!--      :disabled="multiple"-->
      <!--      @click="handleDelete"-->
      <!--      v-hasPermi="['orderManagement:MaintenanceOrder:remove']"-->
      <!--  >删除-->
      <!--  </el-button>-->
      <!--</el-col>-->
      <!--<el-col :span="1.5">-->
      <!--  <el-button-->
      <!--      type="warning"-->
      <!--      plain-->
      <!--      icon="Download"-->
      <!--      @click="handleExport"-->
      <!--      v-hasPermi="['orderManagement:MaintenanceOrder:export']"-->
      <!--  >导出-->
      <!--  </el-button>-->
      <!--</el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="processedMaintenanceOrderList" @selection-change="handleSelectionChange">
      <!--<el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="订单编号" align="center" prop="orderId"/>
      <el-table-column label="服务编号" align="center" prop="serviceId"/>
      <el-table-column min-width="150" label="服务名称" align="center" prop="serviceName"/>
      <el-table-column min-width="150" label="买家" align="center" prop="member.memberName"/>
      <el-table-column min-width="150" label="手机号" align="center" prop="member.phone"/>
      <el-table-column min-width="150" label="商家" align="center" prop="store.storeName"/>
      <el-table-column label="原价" align="center" prop="totalAmount"/>
      <el-table-column label="实付" align="center" prop="actualAmount"/>
      <el-table-column label="优惠" align="center">
        <template #default="scope">
          {{ calculateDiscount(scope.row) }}
        </template>
      </el-table-column>
      <!--<el-table-column label="原价" align="center" prop="originalPrice"/>-->
      <!--<el-table-column label="现价" align="center" prop="currentPrice"/>-->
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="order_type" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="appointmentTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appointmentTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="200" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!--<el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"-->
          <!--           v-hasPermi="['orderManagement:MaintenanceOrder:edit']">修改-->
          <!--</el-button>-->
          <!--<el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"-->
          <!--           v-hasPermi="['orderManagement:MaintenanceOrder:remove']">删除-->
          <!--</el-button>-->
          <el-button
              link
              type="primary"
              icon="View"
              @click="handleDetail(scope.row)"
              v-hasPermi="['storeManagement:storeManagement:detail']"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改洗车订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="MaintenanceOrderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请选择订单状态">
            <el-option
                v-for="dict in order_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间" prop="orderTime">
          <el-date-picker clearable
                          v-model="form.orderTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择下单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker clearable
                          v-model="form.appointmentTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="原价" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入原价"/>
        </el-form-item>
        <el-form-item label="实付" prop="actualAmount">
          <el-input v-model="form.actualAmount" placeholder="请输入实付"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MaintenanceOrder">
import {
  addMaintenanceOrder,
  delMaintenanceOrder,
  getMaintenanceOrder,
  listMaintenanceOrder,
  updateMaintenanceOrder
} from "@/api/orderManagement/maintenanceOrder";
import {parseTime} from "@/utils/ruoyi.js";

const {proxy} = getCurrentInstance();
const {order_type} = proxy.useDict('order_type');

const MaintenanceOrderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeOrderTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: null,
    orderStatus: null,
    orderTime: null,
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

// 修改的地方：处理后的数据
const processedMaintenanceOrderList = computed(() => {
  return MaintenanceOrderList.value.flatMap(order => {
    return order.serviceItem.map(service => {
      return {
        ...order,
        serviceId: service.serviceId,
        serviceName: service.serviceName,
        originalPrice: service.originalPrice,
        currentPrice: service.currentPrice,
        serviceDesc: service.serviceDesc
      };
    });
  });
});

/** 查询洗车订单列表 */
function getList() {
  loading.value = true;
  // queryParams.value.params = {};
  if (null != daterangeOrderTime && '' != daterangeOrderTime) {
    queryParams.value.ext1 = daterangeOrderTime.value[0];
    queryParams.value.ext2 = daterangeOrderTime.value[1];
  }
  console.log(queryParams.value);
  listMaintenanceOrder(queryParams.value).then(response => {
    MaintenanceOrderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderStatus: null,
    verificationCode: null,
    storeId: null,
    orderTime: null,
    appointmentTime: null,
    vehicleId: null,
    memberId: null,
    remark: null,
    totalAmount: null,
    actualAmount: null,
    couponId: null,
    ext1: null,
    ext2: null,
    ext3: null,
    ext4: null,
    ext5: null
  };
  proxy.resetForm("MaintenanceOrderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeOrderTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加洗车订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _orderId = row.orderId || ids.value
  getMaintenanceOrder(_orderId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改洗车订单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["MaintenanceOrderRef"].validate(valid => {
    if (valid) {
      if (form.value.orderId != null) {
        updateMaintenanceOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMaintenanceOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value;
  proxy.$modal.confirm('是否确认删除洗车订单编号为"' + _orderIds + '"的数据项？').then(function () {
    return delMaintenanceOrder(_orderIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('orderManagement/MaintenanceOrder/export', {
    ...queryParams.value
  }, `MaintenanceOrder_${new Date().getTime()}.xlsx`)
}

/** 计算优惠金额 */
const calculateDiscount = (row) => {
  if (row.totalAmount && row.actualAmount) {
    return row.totalAmount - row.actualAmount;
  }
  return 0;
};

getList();
</script>